#include "napi/native_api.h"
#include <hilog/log.h>
#include "./common.h"

struct AsyncWorkInfo {
    napi_async_work work;
    int sum;
};

struct AsyncWorkInfo data = { nullptr, 0 };

static void AExecute(napi_env env, void *data) {
    struct AsyncWorkInfo *arg = (struct AsyncWorkInfo *)data;
    for(int n = 0; n < 100000; n++) {
        arg->sum += 1;
    }
}

static void BComplete(napi_env env, napi_status status, void *data) {
    struct AsyncWorkInfo *arg = (struct AsyncWorkInfo *)data;
    OH_LOG_INFO(LOG_APP, "workB result is %{pubilc}d", arg->sum);
    napi_delete_async_work(env, arg->work);
}

static napi_value executeAsyncWork(napi_env env, napi_callback_info info)
{
    napi_value resourceName;
    napi_create_string_utf8(env, "asyncWork", NAPI_AUTO_LENGTH, &resourceName);
    struct AsyncWorkInfo *ptr = &data;
    napi_create_async_work(env, nullptr, resourceName, AExecute, BComplete, ptr, &ptr->work);
    napi_queue_async_work(env, ptr->work);
    return resourceName;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "executeAsyncWork", nullptr, executeAsyncWork, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version =1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
